'use strict';

const Service = require('egg').Service;
const { Op } = require('sequelize');

class InterviewExperienceService extends Service {
  // 获取经验列表
  async findAll(options = {}) {
    const { ctx } = this;
    const { page = 1, pageSize = 5, keyword } = options;
    
    const where = { status: 1 };
    if (keyword) {
      where[Op.or] = [
        { company_name: { [Op.like]: `%${keyword}%` } },
        { position: { [Op.like]: `%${keyword}%` } }
      ];
    }

    const offset = (page - 1) * pageSize;
    const limit = parseInt(pageSize);

    const { count, rows } = await ctx.model.InterviewExperience.findAndCountAll({
      where,
      attributes: {
        include: [
          [
            ctx.model.literal('(SELECT COUNT(*) FROM experience_comment WHERE experience_comment.experience_id = interview_experience.experience_id)'),
            'comment_count'
          ]
        ]
      },
      order: [['created_at', 'DESC']],
      offset,
      limit,
    });

    return {
      data: rows,
      pagination: {
        current: page,
        pageSize: pageSize,
        total: count,
        pages: Math.ceil(count / pageSize)
      }
    };
  }

  // 根据ID获取经验详情
  async findById(id) {
    const { ctx } = this;
    return await ctx.model.InterviewExperience.findOne({
      where: { 
        experience_id: id,
        status: 1
      },
      attributes: {
        include: [
          [
            ctx.model.literal('(SELECT COUNT(*) FROM experience_comment WHERE experience_comment.experience_id = interview_experience.experience_id)'),
            'comment_count'
          ]
        ]
      },
    });
  }

  // 创建经验
  async create(data) {
    const { ctx } = this;
    return await ctx.model.InterviewExperience.create(data);
  }

  // 删除经验
  async delete(id) {
    const { ctx } = this;
    const result = await ctx.model.InterviewExperience.destroy({
      where: { experience_id: id }
    });
    return result > 0;
  }
}

module.exports = InterviewExperienceService;
